<?php
/**
* All binding of models to other models is handled through this static class.
*
* NOTE: This is NOT the same as Buan's model relationships. "Bindings" are
* intended for use as a general means of establishing links between two specific
* model instances without having to explicity define a model relationship
* between them (using ModelRelation::define())
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/
use Buan\Config;
use Buan\Model;
use Buan\ModelCollection;
use Buan\ModelManager;
abstract class ScribbleBinding {

	/**
	* Bind two models instances together.
	*
	* Creates a BindingModel instance to represent the relationship between the
	* source and target models and returns it.
	*
	* @param ScribbleModel Source model (may be non-persistent)
	* @param ScribbleModel Target model
	* @param string Binding reference to use in this binding
	* @return BindingModel
	*/
	public static function bind($source, $target, $ref) {
		$m = Model::create('Binding');
		$m->ref = $ref;
		$m->source_id = $source->id;
		$m->target_id = $target->id;
		$m->target_type = $target->modelName;
		return $m;
	}

	/**
	* Search the database to find any BindingModel instances that bind the $source
	* model to any instances of the specified target model type.
	*
	* Returns an array containing all found instances.
	*
	* @param ScribbleModel Source model
	* @param string Target model name (ie classname of the model without "Model" suffix)
	* @param string Binding reference to use
	* @return Buan\ModelCollection
	*/
	public static function findBindings($sourceId, $targetModelName, $ref) {
	}

	/**
	* Identical to ScribbleBinding::findBindings() except the returned models
	* are instances of the target model type, rather than instances of
	* BindingModel.
	*
	* @param ScribbleModel Source model
	* @param string Target model name
	* @param string Binding reference to use
	* @return Buan\ModelCollection
	*/
	public static function findModels($sourceId, $targetModelName, $ref) {
		$targetModel = Model::create($targetModelName);
		$dbTblPrefix = Config::get('ext.Scribble.dbTablePrefix');
		$sql = "SELECT t.* FROM {$targetModel->dbTableName} AS t
						LEFT JOIN {$dbTblPrefix}binding AS b ON t.id=b.target_id
						WHERE b.source_id=? AND b.target_model=? AND ref=?";
		$stmt = ModelManager::sqlQuery($sql, array($sourceId, $targetModel->modelName, $ref));
		return new ModelCollection($targetModel->modelName, $stmt);
	}
}
?>